<template>
  <div style="width: 100%">
    <el-collapse v-model="activeName">
      <el-collapse-item :name="1" title="基本信息">
        <el-form :disabled="disabled" size="small" ref="form" :model="formData" label-width="100px"
                 :rules="rules">
          <el-row>
            <el-col :span="12">
              <el-form-item label="中文名称" prop="nameCn">
                <el-input v-model="formData.nameCn"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码标识" prop="name">
                <el-input v-model="formData.name"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="英文名称">
                <el-input v-model="formData.nameEn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="英文描述">
                <el-input v-model="formData.describeEn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="中文描述" prop="describeCn">
                <el-input v-model="formData.describeCn"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-collapse-item>
      <el-collapse-item :name="2" title="编码组合编辑器">
        <div class="option">
          <template v-for="({label,type},index) in optionList">
            <el-button :key="label"
                       :disabled="disabled?true:(type==='sequence'&&disabledBtn)"
                       size="small"
                       @click="add(index)">{{ label }}
            </el-button>
          </template>
        </div>
        <div class="con"></div>
        <draggable tag="ul" class="dUl" :list="codeGroup"
                   v-bind="{group:'optionsGroup', ghostClass: 'ghost', handle: '.drag-option'}">
          <template v-for="(item,index) in codeGroup">
            <li>
              <div style="text-align: center">{{ item.label }}</div>
              <div>
                <span v-if="!disabled" class="el-icon-rank drag-option"></span>
                <component :is="item.component"
                           :key="index"
                           :min="1"
                           :disabled="disabled"
                           v-model="item.value"
                           @change="(v)=>selectChange(v,item.type,index)"
                           size="small">
                  <template v-if="item.type==='date'">
                    <template v-for="{value,name} in dataEnum">
                      <el-option :label="name" :value="value"></el-option>
                    </template>
                  </template>
                  <template v-if="item.type==='attribute'">
                    <el-option v-for="item in attributeList"
                               :label="item.nameCn"
                               :value="item.oid">
                    </el-option>
                  </template>
                </component>
              </div>

              <div class="el-icon-close close_" v-if="!disabled" @click="remove(index)"></div>
            </li>
          </template>
        </draggable>
      </el-collapse-item>
    </el-collapse>

    <div class="md-component-btns">
      <el-button size="medium" v-if="!disabled" type="primary" @click="save">保存</el-button>
      <el-button size="medium" @click="$emit('removeThisTabs')">取消</el-button>
    </div>
  </div>
</template>
<script>
import Draggable from "vuedraggable";

import * as api from "../../../api/settingManage/codeRules"
import {getList} from "@/api/modulManage/attribute";
import {getDic} from "@/api/common";

export default {
  name: "codeRulesTemp",
  components: {Draggable},
  data() {
    return {
      dialogType: "open",

      activeName: [1, 2],
      formData: {
        name: "",
        nameCn: "",
        nameEn: "",
        describeEn: "",
        describeCn: "",
      },
      rules: {
        nameCn: [{required: true, trigger: 'blur', message: "请输入中文名称"}],
        name: [{
          required: true,
          trigger: 'blur',
          message: "请输入编码标识"
        }, {pattern: '^[A-Za-z][A-Za-z0-9_]{1,29}$', message: '请输入正确编码标识'}],
        describeCn: [{required: true, trigger: 'blur', message: "请输入中文描述"}],
      },

      codeGroup: [],
      optionList: [
        {
          label: "属性组件",
          type: "attribute",
          component: "el-select",
          value: "",
        },
        {
          label: "字符组件",
          type: "chars",
          component: "el-input",
          value: ""
        },
        {
          label: "日期组件",
          type: "date",
          component: "el-select",
          value: ""
        },
        {
          label: "序列组件",
          type: "sequence",
          component: "el-input-number",
          value: 0
        },
      ],

      attributeList: [],
      dataEnum: [],
    }
  },
  computed: {
    disabledBtn() {
      return this.codeGroup.filter(item => item.type === "sequence").length !== 0;
    },
    disabled() {
      return this.dialogType === "view";
    }
  },
  methods: {
    selectChange(val, type, index) {
      if (type === "attribute") {
        let names = this.attributeList.map(i => i.oid);
        this.codeGroup[index].oid = this.attributeList[names.indexOf(val)].oid;
      }
    },
    save() {
      this.$refs['form'].validate(f => {
        if (f) {
          let noData = this.codeGroup.filter(item => !item.value);
          if (this.disabledBtn) {
            if (noData.length === 0) {
              let codeRuleJsonList = [];
              this.codeGroup.forEach(item => {
                codeRuleJsonList.push({
                  "type": item.type,
                  "value": item.value,
                })
              })

              let method = this.dialogType === "open" ? "save" : "update";

              api[method]({...this.formData, codeRuleJsonList}).then(() => {
                this.$message.success("保存成功");
                this.$emit('removeThisTabs');
                this.$emit('refresh');
              })
            } else {
              this.$message.warning("请完整填写编码组合组件");
            }
          } else {
            this.$message.warning("编码组合至少包含一个序列组件");
          }
        }
      })
    },

    add(index) {
      this.codeGroup.push(this.deepCopy(this.optionList[index]));
    },
    remove(index) {
      this.codeGroup.splice(index, 1);
    },

    open() {
      this.dialogType = 'open'
    },
    view(row) {
      this.dialogType = 'view'
      api.getDetail({oid: row.oid}).then(res => {
        this.details(res);
      })
    },
    edit(row) {
      this.dialogType = 'edit'
      api.checkout({id: row.oid}).then(res => {
        this.details(res);
        this.$emit('refresh');
      })
    },
    details(res) {
      const data = res.data.data
      this.formData = this.deepCopy(data);
      delete this.formData.codeRuleJson;
      let d = JSON.parse(data.codeRuleJson);

      let l = this.optionList.map(item => item.type);

      if (d && d.length > 0) {
        d.forEach(item => {
          let obj = this.deepCopy(this.optionList[l.indexOf(item.type)]);
          obj.value = item.value;
          this.codeGroup.push(obj)
        })
      }
    }
  },
  mounted() {
    getList({current: 1, size: 999}).then(res => {
      this.attributeList = res.data.data.list;
    })

    getDic("datetype").then(res => {
      this.dataEnum = res.data.data;
    })
  }
}
</script>
<style scoped lang="scss">
.config {
  height: 200px;

  .el-col {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: nowrap;
    height: 36px;
    line-height: 36px;
    font-size: 12px;

    > span {
      width: 40px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      text-align: right;
      padding-right: 10px;
      font-size: 12px;
    }

    .l4 {
      width: 100px;
    }
  }
}

.dUl {
  width: 100%;
  list-style: none;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
  padding-left: 0;

  > li {
    width: calc((100% - 80px) / 4);
    background: #f2f2f2;
    margin-right: 10px;
    margin-bottom: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 5px;
    border-radius: 5px;
    position: relative;

    > div {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      flex-wrap: nowrap;

      > span {
        padding-left: 5px;
        font-size: 18px;
        line-height: 32px;
        color: rgba(86, 84, 84, 0.72);
        cursor: move;
      }

      .el-input {
        width: calc(100% - 30px);
      }

      .el-select {
        width: calc(100% - 30px);
      }

      .el-input-number {
        width: calc(100% - 30px);
      }
    }

    .close_ {
      font-size: 14px;
      width: 16px;
      height: 0;
      line-height: 16px;
      text-align: center;
      background: red;
      color: white;
      position: absolute;
      top: -4px;
      right: -4px;
      border-radius: 100%;
      cursor: pointer;
      overflow: hidden;
      transition: opacity .4s;
      opacity: 0;
    }

    &:hover {
      .close_ {
        opacity: 1;
        height: 16px;
      }
    }
  }


  li:nth-child(4n) {
    margin-right: 0;
  }
}

.option {
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
}
</style>
